package com.mkk.deskTopSearch.view;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import com.mkk.deskTopSearch.util.LogUtil;
import com.mkk.deskTopSearch.util.PropertiesUtil;
import com.mkk.deskTopSearch.util.SearcherManager;
import com.mkk.deskTopSearch.util.SystemUtil;
import com.mkk.deskTopSearch.worker.SearchWorker;

/**
 * 2010-7-11 下午02:10:27 搜索主界面
 */
public class MainFrame extends JFrame {

	private static final long serialVersionUID = 1L;

	/**
	 * constructor
	 */
	public MainFrame() {
		this.main = this;
		this.setTitle(TITLE);
		this.initFrame();
		this.showMe();
	}

	/**
	 * 初始化界面
	 */
	private void initFrame() {
		// logo
		this.setIconImage(SystemUtil.getSystemLogoIcon().getImage());
		// tray
		this.initTrayCompents();
		// north
		this.add(this.showNorthPanel(), BorderLayout.NORTH);
		// center
		this.add(this.showCenterPanel(), BorderLayout.CENTER);
		// south
		this.add(this.showSouthPanel(), BorderLayout.SOUTH);
		// add event
		this.disposeEvent();
		// window event
		this.addWindowListener(getWindowListener());

	}

	/**
	 * 初始化系统托盘组件
	 */
	private void initTrayCompents() {
		if (SystemTray.isSupported()) {
			this.sTray = SystemTray.getSystemTray();
			// 图标
			Image image = SystemUtil.getSystemLogoIcon().getImage();
			// 菜单
			PopupMenu pm = new PopupMenu();
			MenuItem item = new MenuItem("Open");
			item.setActionCommand("open");
			item.addActionListener(this.getActionListener());
			pm.add(item);
			pm.addSeparator();
			item = new MenuItem("Exit");
			item.setActionCommand("close");
			item.addActionListener(this.getActionListener());
			pm.add(item);
			// create
			this.tIcon = new TrayIcon(image, TITLE, pm);
			tIcon.addActionListener(this.getActionListener());
			tIcon.addMouseListener(this.getTrayMouseListener());
			try {
				// add
				this.sTray.add(tIcon);
			} catch (AWTException ex) {
				ex.printStackTrace();
				JOptionPane.showMessageDialog(main, "注意: 该操作系统平台不支持系统托盘", "注意",
						JOptionPane.ERROR_MESSAGE);
			}

		}
	}

	/**
	 * 系统托盘点击事件
	 * 
	 * @return
	 */
	private MouseListener getTrayMouseListener() {
		return new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int b = e.getButton();
				if (b == MouseEvent.BUTTON1) {
					if (e.getClickCount() == 1) {
						if (!main.isVisible()) {
							main.setVisible(true);
							main.setExtendedState(JFrame.NORMAL);
						} else {
							main.setVisible(false);
						}
					}
				}
			}
		};
	}

	/**
	 * 系统托盘菜单点击事件
	 * 
	 * @return
	 */
	private ActionListener getActionListener() {
		return new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				String command = e.getActionCommand();
				if ("open".equalsIgnoreCase(command)) {
					// 显示并正常化显示
					if (!main.isVisible()) {
						main.setVisible(true);
						main.setExtendedState(JFrame.NORMAL);
					}
				} else if ("close".equalsIgnoreCase(command)) {
					int i = JOptionPane.showConfirmDialog(main, "想要离开了吗?",
							"Exit", JOptionPane.OK_CANCEL_OPTION);
					if (i == JOptionPane.OK_OPTION) {
						// close search
						SearcherManager.getSearcherManager().closeSearch();
						System.exit(0);
					}
				}
			}
		};
	}

	/**
	 * 显示北面面板信息
	 * 
	 * @return
	 */
	private JPanel showNorthPanel() {
		JPanel panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		panel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
		this.label1 = new JLabel("[设置]");
		this.label1.setForeground(Color.BLUE);
		this.label1.setToolTipText("设置");
		this.label1.setCursor(new Cursor(Cursor.HAND_CURSOR));
		panel.add(this.label1);
		this.label3 = new JLabel("[首页]");
		this.label3.setToolTipText("首页");
		this.label3.setForeground(Color.BLUE);
		this.label3.setCursor(new Cursor(Cursor.HAND_CURSOR));
		this.label3.setVisible(false);
		panel.add(this.label3);
		return panel;
	}

	/**
	 * 显示中间面板信息
	 * 
	 * @return
	 */
	private JPanel showCenterPanel() {
		panel1 = new JPanel();
		//panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
		Box box = Box.createVerticalBox();
		// 显示搜索框的面板
		JPanel panel2 = new JPanel();
		panel1.setLayout(new FlowLayout(FlowLayout.CENTER));
		this.textfield1 = new JTextField(50);
		this.textfield1.setToolTipText("输入搜索内容");
		this.textfield1.setBackground(Color.WHITE);
		this.textfield1.setBorder(BorderFactory.createLoweredBevelBorder());
		panel2.add(this.textfield1);
		this.button1 = new JButton("搜 索");
		this.button1.setToolTipText("搜索");
		panel2.add(this.button1);
		box.add(Box.createVerticalStrut(180));
		box.add(panel2);
		box.add(Box.createVerticalStrut(250));
		panel1.add(box);
		return panel1;
	}

	/**
	 * 处理事件方法
	 */
	private void disposeEvent() {
		// 首选项事件
		this.label1.addMouseListener(new MouseAdapter() {
			public void mouseEntered(MouseEvent e) {
				setInfo("设置你的搜索习惯...", Color.GRAY);
			}

			public void mouseExited(MouseEvent e) {
				setInfo("欢迎使用桌面搜索系统", Color.GRAY);
			}

			public void mouseClicked(MouseEvent e) {
				setDialog = new SetDialog(main, true);
				Point p = SystemUtil.getStartPoint(setDialog.getWidth(),
						setDialog.getHeight());
				setDialog.setLocation(p);
				setDialog.setVisible(true);
			}
		});
		/*
		 * 搜索事件
		 */
		final ActionListener listener1 = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// 1.获取搜索关键字
				String s = textfield1.getText().trim();
				if (s.length() == 0) {
					setInfo("输入为空,不能搜索...", Color.BLUE);
					return;
				}
				try {
					setInfo("搜索中,请稍候...", Color.BLUE);
					// 2.提交搜索
					SearchWorker worker = new SearchWorker(s, jProgressBar1);
					worker.execute();
					if (worker.get().equals(Boolean.TRUE)) {
						setInfo("搜索完成!", Color.BLUE);
						// 创建显示搜索结果面板
						searchPanel = new SearchResultPanel(s, worker
								.getResList(), worker.getTimes(),
								MainFrame.this);
						// 替换
						main.remove(panel1);
						main.add(searchPanel, BorderLayout.CENTER);
						main.validate();
						searchPanel.getTextField1().requestFocus();
						label3.setVisible(true);
					} else {
						setInfo("搜索异常...", Color.RED);
						JOptionPane.showMessageDialog(main, "搜索出现异常,信息:\n"
								+ worker.getErrorInfo() + "\n检查是否创建索引!", "异常",
								JOptionPane.ERROR_MESSAGE);
					}
				} catch (Exception ex) {
					setInfo("搜索异常...", Color.RED);
					JOptionPane.showMessageDialog(main, "搜索出现异常,信息:\n"
							+ ex.getMessage(), "异常", JOptionPane.ERROR_MESSAGE);
					ex.printStackTrace();
					// save exception log
					LogUtil.saveExceptionLog(ex);
				}
			}

		};
		this.textfield1.addActionListener(listener1);
		this.button1.addActionListener(listener1);

		/*
		 * 搜索提示事件
		 */
		// this.textfield1.addKeyListener(new KeyAdapter() {
		// public void keyReleased(KeyEvent e) {
		// String s = textfield1.getText().trim();
		// if (s.length() > 0) {
		// executeSearch(s);
		// } else {
		// // 没有则销毁提示框
		// if (window1 != null) {
		// if (window1.isVisible()) {
		// MainFrame.this.window1.setVisible(false);
		// textfield1.requestFocus();
		// // main.validate();
		// }
		// }
		// }
		// }
		// });
		// 回首页事件
		this.label3.addMouseListener(new MouseAdapter() {

			public void mouseEntered(MouseEvent e) {
				setInfo("返回桌面搜索主界面...", Color.GRAY);
			}

			public void mouseExited(MouseEvent e) {
				setInfo("欢迎使用桌面搜索系统", Color.GRAY);
			}

			public void mouseClicked(MouseEvent e) {
				if (searchPanel != null) {
					main.remove(searchPanel);
					main.add(showCenterPanel(), BorderLayout.CENTER);
					// 注意:此处的处理感觉不是很好
					textfield1.addActionListener(listener1);
					button1.addActionListener(listener1);
					main.validate();
					panel1.repaint();
					label3.setVisible(false);
					textfield1.requestFocus();
				}
			}
		});
	}

	/**
	 * 提示框搜索
	 */
	// private void executeSearch(final String keyWord) {
	// EventQueue.invokeLater(new Runnable() {
	// public void run() {
	// Object os[] = SearchHelp.search(keyWord);
	// if (os.length > 0) {
	// // 显示搜索帮助框
	// showQuickWindow(os);
	// } else {
	// // 没有则销毁提示框
	// if (window1 != null) {
	// if (window1.isShowing()) {
	// MainFrame.this.window1.dispose();
	// textfield1.requestFocus();
	// // main.validate();
	// }
	// }
	// }
	// }
	//
	// });
	//
	// }

	/**
	 * 显示搜索时的提示框
	 * 
	 * @param result
	 */
	// private void showQuickWindow(Object[] result) {
	// this.window1 = new JWindow(main);
	// Point p = this.textfield1.getLocationOnScreen();
	// this.window1.setLocation(p.x, p.y + 20);
	// Dimension dim = this.textfield1.getSize();
	// this.window1.setSize(dim.width, 50);
	// this.list1 = new JList(result);
	// this.list1.setBackground(Color.WHITE);
	// this.window1.add(this.list1);
	// this.window1.setVisible(true);
	// textfield1.requestFocus();
	// // this.main.validate();
	// }

	/**
	 * 南边界面
	 * 
	 * @return
	 */
	private JPanel showSouthPanel() {
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
		panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		this.label2 = new JLabel();
		this.setInfo("欢迎使用桌面搜索系统", Color.BLACK);
		panel.add(this.label2);
		panel.add(Box.createHorizontalStrut(490));
		this.jProgressBar1 = new JProgressBar(JProgressBar.HORIZONTAL);
		this.jProgressBar1.setVisible(false);
		panel.add(this.jProgressBar1);

		return panel;
	}

	public JProgressBar getjProgressBar1() {
		return jProgressBar1;
	}

	/**
	 * 设置状态栏显示的信息
	 * 
	 * @param info
	 * @param c
	 */
	void setInfo(String info, Color c) {
		this.label2.setText(info);
		this.label2.setForeground(c);
	}

	/**
	 * 关闭时的界面
	 * 
	 * @return
	 */
	private JPanel closePanel() {
		JPanel p = new JPanel();
		p.setLayout(new BorderLayout());
		JLabel l = new JLabel("选择关闭操作:");
		l.setForeground(Color.LIGHT_GRAY);
		p.add(l, BorderLayout.NORTH);
		JPanel p2 = new JPanel();
		ButtonGroup bg = new ButtonGroup();
		radioButton1 = new JRadioButton("退出系统");
		radioButton1.setSelected(true);
		radioButton2 = new JRadioButton("最小化到系统托盘");
		bg.add(radioButton1);
		bg.add(radioButton2);
		p2.add(radioButton1);
		p2.add(radioButton2);
		p.add(p2, BorderLayout.CENTER);
		checkBox1 = new JCheckBox("下次关闭时不再提示");
		checkBox1.setForeground(Color.GRAY);
		p.add(checkBox1, BorderLayout.SOUTH);
		return p;
	}

	/**
	 * 显示界面
	 */
	private void showMe() {
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.setLocation(SystemUtil
				.getStartPoint(DEFAULT_WIDTH, DEFAULT_HEIGHT));
		this.setVisible(true);

	}

	/**
	 * 窗口事件
	 * 
	 * @return
	 */
	private WindowListener getWindowListener() {
		WindowListener li = new WindowAdapter() {

			// 关闭窗口时
			@Override
			public void windowClosing(WindowEvent e) {
				// 若操作系统不支持系统托盘则直接关闭
				if (!SystemTray.isSupported()) {
					SearcherManager.getSearcherManager().closeSearch();
					System.exit(0);
				}
				if (PropertiesUtil.isShowClosePanel()) {
					int i = JOptionPane.showConfirmDialog(main, closePanel(),
							"Exit", JOptionPane.OK_CANCEL_OPTION);
					if (i == JOptionPane.OK_OPTION) {
						if (radioButton1.isSelected()) {
							PropertiesUtil.setCloseChooser(true);
							SearcherManager.getSearcherManager().closeSearch();
							System.exit(0);
						}
						if (radioButton2.isSelected()) {
							PropertiesUtil.setCloseChooser(false);
							main.setVisible(false);
						}
					}
					PropertiesUtil.setShowClosePanel(!checkBox1.isSelected());
				} else {
					// 不显示则根据其选择的操作来处理
					if (PropertiesUtil.getCloseChooser()) {
						// 关闭
						System.exit(0);
					} else {
						// 最小化到系统托盘
						main.setVisible(false);
					}
				}
			}

			// 最小化时
			@Override
			public void windowIconified(WindowEvent e) {
				main.setVisible(false);
			}
		};
		return li;
	}

	public static void main(String... strings) {
		SystemUtil.setUI();
		new MainFrame();
	}

	// 界面默认大小值
	private static final int DEFAULT_WIDTH = 800;
	private static final int DEFAULT_HEIGHT = 566;
	// 标题
	private static final String TITLE = "桌面搜索 1.0";
	// 首选项标签
	private JLabel label1;
	// 中间面板对象
	private JPanel panel1;
	// 搜索框
	private JTextField textfield1;
	// 搜索按钮
	private JButton button1;
	// 状态栏
	private JLabel label2;
	// 进度条
	private JProgressBar jProgressBar1;
	// 搜索帮助提示框
	// private JWindow window1;
	// 提示框中的组件
	// private JList list1;
	// self
	private MainFrame main;
	// setdialog
	private SetDialog setDialog;
	// 回首页
	private JLabel label3;
	// 搜索面板
	private SearchResultPanel searchPanel;
	// 系统托盘相关
	private TrayIcon tIcon;
	private SystemTray sTray;
	private JCheckBox checkBox1;
	private JRadioButton radioButton1;
	private JRadioButton radioButton2;

}
